package huichun_m

import (
	"frozen-go-mini/common/domain"
	"frozen-go-mini/common/resource/mysql"
	"gorm.io/gorm/clause"
	"time"
)

type UserFootprint struct {
	mysql.Entity
	UserId    mysql.ID `gorm:"column:user_id"`    //  用户id
	ProductId mysql.ID `gorm:"column:product_id"` //  商品id
}

func (UserFootprint) TableName() string {
	return "user_footprint"
}

// 增加用户足迹
func AddUserFootprint(model *domain.Model, footprint UserFootprint) error {
	if err := model.DB().Model(UserFootprint{}).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "user_id"}, {Name: "product_id"}},
		DoUpdates: clause.Assignments(map[string]interface{}{
			"updated_time": time.Now(),
		}),
	}).Create(&footprint).Error; err != nil {
		model.Log.Errorf("AddUserFootprint fail:%v", err)
		return err
	}
	return nil
}

// 获取我的足迹
func GetMyFootprint(model *domain.Model, userId mysql.ID) []HuichunProduct {
	var res []HuichunProduct
	if err := model.DB().Table(HuichunProduct{}.TableName()+" p").
		Joins("INNER JOIN "+UserFootprint{}.TableName()+" u").
		Select("p.*").
		Where("u.product_id = p.id").Where("p.status = 1").
		Where("u.user_id = ?", userId).
		Order("u.updated_time DESC").Find(&res).Error; err != nil {
		model.Log.Errorf("GetMyFootprint fail:%v", err)
	}
	return res
}
